
accessid = ''
accesskey = ''
host = ''
policyBase64 = ''
signature = ''
callbackbody = ''
filename = ''
key = ''
expire = 0
g_object_name = ''
g_object_name_type = ''
imgstr=''
delImgStr=''
now = timestamp = Date.parse(new Date()) / 1000;
function send_requestMp3() {
    var xmlhttp = null;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    key='dingyuan/activity2020/'+$("#orgId").val()+'/'
    if (xmlhttp != null) {
        serverUrl = '/marketing/ossSignature?dir='+key;
        xmlhttp.open("GET", serverUrl, false);
        xmlhttp.send(null);
        return xmlhttp.responseText
    } else {
        alert("Your browser does not support XMLHTTP.");
    }
};

function get_signatureMp3() {
    //可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
    now = timestamp = Date.parse(new Date()) / 1000;
    if (expire < now + 60*50) {
        body = send_requestMp3()
        var obj = eval("(" + body + ")");
        console.log(obj)
        host = obj['host']
        policyBase64 = obj['policy']
        accessid = obj['accessid']
        signature = obj['signature']
        expire = parseInt(obj['expire'])
        callbackbody = obj['callback']
        key = obj['dir']
        return true;
    }
    return false;
};

function random_stringMp3(len) {
    len = len || 32;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var maxPos = chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

//获取后缀
function get_suffixMp3(file) {
    pos = file.name.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = file.name.substring(pos)
    }
    return suffix;
}
function get_uploaded_object_nameMp3(file) {

    g_object_name = $("#id").val()+".mp3";
    console.log(g_object_name);
    return g_object_name
}

function set_upload_paramMp3(up, file, ret) {
    console.log(up.files)
    if (ret == false) {
        ret = get_signatureMp3()
    }
    //g_object_name = key;
    if (file != '') {
        get_uploaded_object_nameMp3(file)
    }
    new_multipart_params = {
        'key': key+g_object_name,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid,
        'success_action_status': '200', //让服务端返回200,不然，默认会返回204
        'callback': callbackbody,
        'signature': signature,
    };

    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });
}

function previewImageMp3(file, callback) {
    if (file.type == 'image/gif') {
        var fr = new mOxie.FileReader();
        fr.onload = function () {
            callback(fr.result);
            fr.destroy();
            fr = null;
        }
        fr.readAsDataURL(file.getSource());
    } else {
        var preloader = new mOxie.Image();
        preloader.onload = function () {
            var imgsrc = preloader.type == 'image/jpeg' ? preloader.getAsDataURL('image/jpeg', 80) : preloader.getAsDataURL();
            callback && callback(imgsrc);
            preloader.destroy();
            preloader = null;
        };
        preloader.load(file.getSource());
    }
}
var uploaderMp3 = new plupload.Uploader({
    runtimes: 'html5,flash,silverlight,html4',
    browse_button: 'uploadMusic',
    //multi_selection: false,
    flash_swf_url: '../lib/plupload-2.1.2/js/Moxie.swf',
    silverlight_xap_url: '../lib/plupload-2.1.2/js/Moxie.xap',
    url: 'http://oss.aliyuncs.com',
    filters: {
        mime_types: [ //只允许上传mp3文件
            {
                title: "audio files",
                extensions: "mp3"
            }
        ],
        max_file_size: '3mb', //最大只能上传3mb的文件
        prevent_duplicates: true //不允许选取重复文件
    },

    init: {
        PostInit: function () {
            imgstr='';
            set_upload_paramMp3(uploaderMp3, '', false);
        },

        FilesAdded: function (up, files) {
            console.log(files)
            uploaderMp3.start();
        },

        BeforeUpload: function (up, file) {
            set_upload_paramMp3(up, file, true);
        },

        UploadProgress: function (up, file) {
            // var d = document.getElementById(file.id);
            // d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
            // var prog = d.getElementsByTagName('div')[0];
            // var progBar = prog.getElementsByTagName('div')[0]
            // progBar.style.width = 3 * file.percent + 'px';
            // progBar.setAttribute('aria-valuenow', file.percent);
        },

        FileUploaded: function (up, file, info) {

            if (info.status == 200) {
                document.getElementById('uploadStatus').innerHTML = '图片上传成功, 文件名:' + get_uploaded_object_nameMp3(file);
                if(imgstr) {
                    imgstr +=  get_uploaded_object_nameMp3(file)+"SPLIT"
                } else {
                    imgstr = get_uploaded_object_nameMp3(file)+"SPLIT";
                }
                // var imgstrAA="asdfs2342fsadfasdfasefsaasdfs2342fsadfasdfasefsa";
                // console.log("@@@"+imgstr);
                $.cookie('imgStr',imgstr);
                //console.log("66666666666");
            } else {
                document.getElementById('uploadStatus').innerHTML = info.response;
            }

        },

        Error: function (up, err) {
            if (err.code == -600) {
                layer.msg("选择的图片太大了");
                //document.getElementById('console').appendChild(document.createTextNode("\n选择的文件太大了,可以根据应用情况，在upload.js 设置一下上传的最大大小"));
            } else if (err.code == -601) {
                layer.msg("请选择正确格式的图片");
                //document.getElementById('console').appendChild(document.createTextNode("\n选择的文件后缀不对,可以根据应用情况，在upload.js进行设置可允许的上传文件类型"));
            } else if (err.code == -602) {
                layer.msg("这个文件已经上传过一遍了");
                //document.getElementById('console').appendChild(document.createTextNode("\n这个文件已经上传过一遍了"));
            } else {
                layer.msg(err.response);
                //document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
            }
        }
    }
});

uploaderMp3.init();

/*删除图片*/
$('#cardFrontImg').on('click', '.delete_btn', function() {
    var files = uploaderMp3.files;
    var id = $(this).attr('id');
    console.log("*****************************");
    console.log(id);
    for(var i = 0; i < files.length; i++) {
        var filename = get_uploaded_object_nameMp3(files[i])
        if( filename == id) {
            console.log("+++++++++++++++++++++++++++");
            console.log(filename);
            imgstr=imgstr.replace(filename+"SPLIT","");
            console.log(imgstr);
            $.cookie('imgStr',null);
            $.cookie('imgStr',imgstr);
            //delImgs(filename,$("#orgId").val(),uploader,this);//与后台交互，删除图片


            $.ajax({
                url:'/marketing/delImgs',
                type:'POST', //GET
                async:true,    //或false,是否异步
                data:{
                    id:filename,
                    orgId:$("#orgId").val()
                },
                timeout:5000,    //超时时间
                dataType:'json',    //返回的数据格式：json/xml/html/script/jsonp/text
                beforeSend:function(xhr){
                    /*console.log(xhr)
                     console.log('发送前')*/
                },
                success:function(data){
                    console.log(data);
                    if (data.code='000000'){

                    }else {
                        layer.msg("删除失败");
                    }
                },
                error:function(xhr,textStatus){
                    console.log('错误')
                    console.log(xhr)
                    console.log(textStatus)
                },
                complete:function(){
                    //console.log('结束')
                }
            });

            uploaderMp3.removeFile(files[i]);
            $(this).parent('.imgBox').remove();
        }
    }
})

